package com.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution1466 {
    public int minReorder(int n, int[][] connections) {
        int res = 0;
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(new ArrayList<>());
        }
        for (int i = 0; i < connections.length; i++) {
            list.get(connections[i][0]).add(i);
            list.get(connections[i][1]).add(i);
        }
        LinkedList<Integer> queue = new LinkedList<>();
        queue.add(0);
        boolean[] visited = new boolean[connections.length];
        while (!queue.isEmpty()) {
            int cur = queue.removeFirst();
            List<Integer> curList = list.get(cur);
            for (int x : curList) {
                if (!visited[x]) {
                    visited[x] = true;
                    int from = connections[x][0];
                    int to = connections[x][1];
                    res += from == cur ? 1 : 0;
                    queue.add(from == cur ? to : from);
                }
            }
        }
        return res;
    }
}
